from .base import BaseModel
from ..extensions.extensions import db
from werkzeug.security import generate_password_hash, check_password_hash

class User(BaseModel):
    __tablename__ = 'users'
    
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column('password', db.String(100), nullable=False)
    salt = db.Column(db.String(20))
    real_name = db.Column(db.String(50))
    avatar = db.Column(db.String(200))
    email = db.Column(db.String(100))
    mobile = db.Column(db.String(20))
    status = db.Column(db.Boolean, nullable=False, default=True)
    dept_id = db.Column(db.Integer)
    last_login_time = db.Column(db.DateTime)
    last_login_ip = db.Column(db.String(50))
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'real_name': self.real_name,
            'avatar': self.avatar,
            'email': self.email,
            'mobile': self.mobile,
            'status': self.status,
            'dept_id': self.dept_id,
            'last_login_time': self.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if self.last_login_time else None,
            'last_login_ip': self.last_login_ip,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    @property
    def password_hash(self):
        """获取密码"""
        return self.password
        
    @password_hash.setter
    def password_hash(self, password):
        """设置密码"""
        self.password = generate_password_hash(password)
        
    def verify_password(self, password):
        """验证密码"""
        return check_password_hash(self.password, password) 